// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()

const tcbRouter = require('tcb-router') // 导入路由工具
const db = cloud.database()

const commentCollection = db.collection('blog') // 消息列表
const detailCommentCollection = db.collection('blog-comment') // 评论列表

const MAX_LIMIT = 100 // 最大限制条数

// 云函数入口函数
exports.main = async (event, context) => {
  const app = new tcbRouter({ // 需要将event 传入tcbRouter
	  event
  })
  // 获取消息列表
  app.router('list', async (ctx, next) => {
	  const keyword = event.keyword // 拿到输入的内容
	  let words = {}
	  if (keyword.trim() !== '') {
		  words = {
			  content: db.RegExp({
				  regexp: keyword,
				  options: 'i' // 忽略大小写
			  })
		  }
	  }
	  let commentList = await commentCollection
							.where(words)
							.skip(event.start)
							.limit(event.count)
							.orderBy('createTime', 'desc') // 倒序
							.get()
							.then(res => {
								return res.data
							})
		ctx.body = commentList
  })
  // 获取单个消息信息和对应的评论列表
  app.router('detail', async (ctx, next) => {
	  let blogId = event.commentId
	  let detail = await commentCollection
						  .where({
							  _id: blogId
						  })
						  .get()
						  .then(res => {
							  return res.data
						  })
		
		const commentCountResult = await commentCollection.count()
		// count得到的是一个对象 里面的total是总条数
		const commentTotal = commentCountResult.total
		let commentDetailList = {
			data: []
		}
		if (commentTotal > 0) {
			const batchTimes = Math.ceil(commentTotal / MAX_LIMIT)
			const tasks = []
			for (let i = 0; i < batchTimes; i++) {
				let promise = detailCommentCollection
					.skip(i * MAX_LIMIT)
					.limit(MAX_LIMIT)
					.where({
						blogId
					})
					.orderBy('createTime', 'desc')
					.get()
				tasks.push(promise)
				if (tasks.length > 0) {
					commentDetailList = (await Promise.all(tasks)).reduce((acc, cur) => {
						return {
							data: acc.data.concat(cur.data)
						}
					})
				}
			}
		}
		ctx.body = {
			detail,
			commentDetailList
		}
  })
  
  // 拿到对应自己发布的信息
  const { OPENID } = cloud.getWXContext()
  app.router('getOwnList', async (ctx, next) => {
  	ctx.body = await commentCollection.where({
  		_openid: OPENID
  	})
  	.skip(event.start)
  	.limit(event.count)
  	.orderBy('createTime', 'desc')
  	.get()
  	.then(res => {
  		return res.data
  	})
  })
  
  // 拿到自己的评论
  app.router('getOwnComment', async (ctx, next) => {
	  ctx.body = await detailCommentCollection.where({
		  _openid: OPENID
	  })
	  .skip(event.start)
	  .limit(event.count)
	  .orderBy('createTime', 'desc')
	  .get()
	  .then(res => {
	  	return res.data
	  })
  })
  return app.serve()
}